package com.heima.platform.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.platform.dtos.AdUserDto;
import com.heima.model.platform.pojos.AdUser;
import com.heima.platform.mapper.AdUserMapper;
import com.heima.platform.service.AdUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tmh
 * @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
 * @createDate 2023-08-27 15:16:32
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
        implements AdUserService {

    @Resource
    private AdUserMapper adUserMapper;

    /**
     * 管理员登录
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult adminUserLogin(AdUserDto adUserDto) {
        //1.判断参数是否为空
        if (adUserDto == null&& StringUtils.isBlank(adUserDto.getName())&&StringUtils.isBlank(adUserDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.数据库查询用户是否存在
        String username = adUserDto.getName();

        AdUser dbAdUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, username));
        if (dbAdUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户信息不存在");
        }
        //3.判断密码是否相同
        //3.1得到盐
        String salt = dbAdUser.getSalt();
        String password = adUserDto.getPassword();
        //3.2比对密码
        if (!dbAdUser.getPassword().equals(DigestUtils.md5DigestAsHex((password + salt).getBytes()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.返回数据 jwt user
        Map<String,Object> map=new HashMap<>();
        String token = AppJwtUtil.getToken(dbAdUser.getId().longValue());
        dbAdUser.setId(null);
        dbAdUser.setPassword(null);
        map.put("token",token);
        map.put("user",dbAdUser);

        return ResponseResult.okResult(map);
    }
}




